<script lang="ts">
export default {
  name: "RepoCompEntityTable"
}
</script>

<template>
  <!-- 数据表单 -->
  <el-table
      ref="dataTableRef"
      v-loading="false"
      :data="dataState.entityList"
      border
      highlight-current-row
      @row-click="handleRowClick"
  >
    <!-- 展开列表 -->
    <el-table-column type="expand">
      <template #default="props">
        <el-form-item>
          <el-input v-model="props.row.description" :autosize="{ minRows: 3, maxRows: 100 }" :readonly="true"
                    type="textarea"/>
        </el-form-item>
        <el-table
            ref="dataTableRef"
            :data="props.row.versions"
            border
            highlight-current-row
            @row-click="handleRowClick"
        >
          <el-table-column align="center" label="版本号" min-width="100" prop="version"/>
          <el-table-column align="center" label="版本状态" min-width="100" prop="stage"/>
          <el-table-column align="center" label="组件" min-width="100" prop="component"/>
          <el-table-column align="center" label="MD5" min-width="200" prop="md5"/>
          <el-table-column :formatter="formatFileSize4elTableColumn" label="文件大小" prop="fileSize"
                           width="110"/>
          <el-table-column :formatter="formatDate4elTableColumn" align="center" label="创建时间" min-width="100"
                           prop="createTime"/>
          <el-table-column :formatter="formatDate4elTableColumn" align="center" label="更新时间" min-width="100"
                           prop="updateTime"/>
          <el-table-column align="center" label="操作" width="160">
            <template #default="scope">
              <el-button :icon="Download" circle plain type="primary" @click.stop="handleDownload(scope.row)"/>
              <el-button :icon="Edit" circle plain type="primary" @click.stop="handleEditVersion(scope.row)"/>
              <el-button :icon="Delete" circle plain type="danger" @click.stop="handleDeleteVersion(scope.row)"/>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-table-column>

    <!-- 列表 -->
    <el-table-column label="设备厂商" min-width="150" prop="manufacturer"/>
    <el-table-column label="设备类型" min-width="150" prop="deviceType"/>
    <el-table-column label="模块名称" min-width="150" prop="modelName"/>
    <el-table-column label="属组" min-width="150" prop="groupName"/>
    <el-table-column v-if="props.modelType === 'service' " label="组件类型" min-width="90" prop="component"/>
    <el-table-column label="最新版本" prop="lastVersion.version" width="90"/>
    <el-table-column :formatter="formatFileSize4elTableColumn2" label="文件大小" prop="lastVersion.fileSize" width="80"/>
    <el-table-column label="所有者" prop="ownerId" width="150"/>

    <!-- 上传对话框/下载对话框 -->
    <el-table-column align="center" label="操作" width="240">
      <template #default="scope">
        <el-upload
            v-model:file-list="dataState.fileList"
            :before-upload="handleBeforeUpload"
            :http-request="(file)=>{return handleUpload(file,scope.row)}"
            :show-file-list="false"
            accept=".jar,.tar,.gz"
        >
          <el-button :icon="Key" circle plain type="primary" @click.stop="handleKeyDialog(scope.row)"/>
          <el-button slot="trigger" :icon="Upload" circle plain type="primary"/>
          <el-button :icon="Download" circle plain type="primary" @click.stop="handleDownload(scope.row)"/>
          <el-button :icon="Edit" circle plain type="primary" @click.stop="handleEditDialog(scope.row)"/>
          <el-button :icon="Delete" circle plain type="danger" @click.stop="handleDelete(scope.row)"/>
        </el-upload>
      </template>
    </el-table-column>

  </el-table>

  <!-- 分页工具条 -->
  <pagination v-if="dataState.total > 0" v-model:limit="dataState.queryParams.pageSize"
              v-model:page="dataState.queryParams.pageNum" :total="dataState.total"
              @pagination="handleQuery"/>
</template>

<script lang="ts" setup>
import {onMounted, reactive} from "vue";

import {
  CreateRepoCompRequestVO,
  RepoCompEntity,
  RepoCompQueryParam, RepoCompVerItem
} from "@/api/cloud/repository/repocomp/file/types";
import {
  listRepoCompEntityPages,
} from "@/api/cloud/repository/repocomp/file";
import {Key, Download, Upload, Delete, Edit} from '@element-plus/icons-vue';
import {
  ElMessage,
  ElUpload,
  UploadRawFile,
  UploadRequestOptions,
  UploadUserFile,
} from 'element-plus';
import {formatDate4elTableColumn,} from '@/utils/formatter';
import {formatFileSize4elTableColumn, formatFileSize4elTableColumn2} from '@/utils/fileutil';
import {uploadFile, downloadFiles} from '@/api/cloud/repository/fileupload';

const props = defineProps(['modelType'])
const emit = defineEmits(['rowClick', 'update', 'delete', 'deleteVersion', 'updateVersion', 'updateKey']);// 定义组件的事件通知

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({refreshTable});

// 数据状态：定义
let dataState = reactive({
  // 页面转载状态
  loading: false,
  // 选中ID数组
  ids: [],
  // 记录总数
  total: 0,
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 查询参数
  queryParams: {pageNum: 1, pageSize: 10} as RepoCompQueryParam,
  // 实体数据
  entityList: [] as RepoCompEntity[],
  // 文件列表
  fileList: [] as UploadUserFile[],
});


/**
 * 捕获列表中的行选择
 * @taskParam row
 */
function handleRowClick(row: any) {
  emit('rowClick', row);
}


/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
  if (file.size > 100 * 1048 * 1048) {
    ElMessage.warning('上传文件不能大于100M');
    return false;
  }

  return true;
}

/**
 * 捕获按钮的打开对话框操作：create/update
 * @taskParam row 行信息
 */
function handleEditDialog(row: any) {
  emit('update', 'table', 'update', row);
}

function handleKeyDialog(row: any) {
  emit('updateKey', row);
}

async function handleUpload(options: UploadRequestOptions, row: any): Promise<any> {
  // 上传API调用
  uploadFile(options.file, row.modelName, row.modelType, row.modelVersion, row.component, '').then(() => {
    dataState.fileList = [];
    ElMessage.success('上传成功！');

    handleQuery();
  })
}

function handleDownload(row: any) {
  let data = {
    modelName: '',
    modelType: '',
    modelVersion: '',
    version: '',
    pathName: '',
  } as CreateRepoCompRequestVO;

  // 根据结构，获得版本信息
  let version = {} as RepoCompVerItem;
  if (row.lastVersion !== undefined) {
    version = row.lastVersion;
  }
  if (row.version !== undefined) {
    version = row;
  }

  data.modelName = row.modelName;
  data.modelType = row.modelType;
  data.modelVersion = row.modelVersion;
  data.version = version.version;
  data.pathName = version.pathName;

  let fileName = data.modelName + '-' + data.version + '.tar';
  let uri = 'http://repository.fox-tech.cn/' + data.modelType + '/' + data.modelName + '/' + data.modelVersion + '/' + data.version + '/' + data.pathName;
  downloadFiles(fileName, uri);
}

/**
 * 刷新页面信息
 */
function handleQuery() {
  emit('rowClick', {});

  dataState.loading = true;

  dataState.queryParams.modelType = props.modelType;

  dataState.entityList = [];
  listRepoCompEntityPages(dataState.queryParams).then(({data}) => {
    data.list.forEach(value => {
      value.versions?.forEach(ver => {
        ver.modelName = value.modelName;
        ver.modelType = value.modelType;
        ver.modelVersion = value.modelVersion;
      });
      dataState.entityList.push(value);
    });

    dataState.total = data.total;
    dataState.loading = false;
  });
}

function handleDelete(row: any) {
  emit('delete', row);
}

function handleDeleteVersion(row: any) {
  emit('deleteVersion', row);
}

function handleEditVersion(row: any) {
  emit('updateVersion', row);
}

/**
 * 刷新表单
 */
function refreshTable(queryParams: RepoCompQueryParam) {
  dataState.queryParams = queryParams;
  if (dataState.queryParams.ownerId === '') {
    dataState.queryParams.ownerId = undefined;
  }
  if (dataState.queryParams.groupName === '') {
    dataState.queryParams.groupName = undefined;
  }
  if (dataState.queryParams.modelType === '') {
    dataState.queryParams.modelType = undefined;
  }
  if (dataState.queryParams.modelVersion === '') {
    dataState.queryParams.modelVersion = undefined;
  }
  if (dataState.queryParams.modelName === '') {
    dataState.queryParams.modelName = undefined;
  }
  if (dataState.queryParams.component === '') {
    dataState.queryParams.component = undefined;
  }

  handleQuery();
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  let param = location.search.split('?')[1];
  let searchParams = new URLSearchParams(param);
  let modelName = searchParams.get('modelName') as string;
  let modelVersion = searchParams.get('modelVersion') as string;

  dataState.queryParams.modelType = props.modelType;

  // 如果地址栏填写了查询参数
  if (modelName !== null && modelVersion !== null) {
    dataState.queryParams.modelName = modelName;
    dataState.queryParams.modelVersion = modelVersion;
  }

  // 查询实体数据
  handleQuery();
});

</script>
